package java67_adv9;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.Socket;

//聊天的线程
public class FileThread2 extends Thread {
	private Socket s;

	public FileThread2(Socket s) {
		this.s = s;
		super.setName(String.valueOf(s.getInetAddress()));

	}

	// 这个一个目录,所有的文件从这里找
	public static final String PATH = "C:/Users/Administrator/Desktop/pic";
	// public static final String PATH = "/opt/javademo/pic";

	@Override
	public void run() {
		// 先从客户端那里获得要下载的文件名,发送给客户端
		System.out.println(s.getInetAddress() + ":" + s.getPort() + "连接上了...");
		try {
			InputStream in = s.getInputStream();
			OutputStream out = s.getOutputStream();
			BufferedReader br = new BufferedReader(new InputStreamReader(in));
			String fileName = br.readLine();// 读到换行结束 \n
			FileInputStream fin = new FileInputStream(new File(PATH, fileName));
			byte[] b = new byte[fin.available()];//
			fin.read(b);
			fin.close();
			out.write(b);
			out.flush();
			System.out.println(fileName + "文件发送给" + s.getInetAddress() + "成功");
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} finally {
			if (s != null)
				try {
					s.close();
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
		}
	}
}
